
//
//  DoorSystemPwdSettingViewController.m
//  RONGAO
//
//  Created by ZhangYeKun on 2017/2/24.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorSystemPwdSettingViewController.h"
#import "DSChangePwdTableViewCell.h"
#import "PasswordAletView.h"
@interface DoorSystemPwdSettingViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;

/** 开锁密码 **/
@property(nonatomic,strong) NSString *doorpassword;

/** 弹出框 **/
@property(nonatomic,strong) PasswordAletView *pwdAlertView;

/** indextag **/
@property(nonatomic,assign) NSInteger indextag;

@end

@implementation DoorSystemPwdSettingViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [AppDelegate globalDelegate].cameraModel.delegate2 = self;
    SMsgAVIoctrlSetDoorPasswordModeReq *s = malloc(sizeof(SMsgAVIoctrlSetDoorPasswordModeReq));
    memset(s, 0, sizeof(SMsgAVIoctrlSetDoorPasswordModeReq));
    
    [[AppDelegate globalDelegate].cameraModel sendIOCtrlToChannel:0
                                                             Type:IOTYPE_USER_IPCAM_GET_DOORPASSWORDMODE_REQ
                                                             Data:(char *)s
                                                         DataSize:sizeof(SMsgAVIoctrlSetDoorPasswordModeReq)];
    free(s);

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationStyle];
    [self masLayoutSubview];
    
    __weak typeof(self) weakself = self;
    
    

    PasswordAletView *view = [[[NSBundle mainBundle]loadNibNamed:@"PasswordAletView" owner:self options:nil]lastObject];
    view.frame = self.view.bounds;
    self.pwdAlertView = view;
    self.pwdAlertView.title.text = @"设备密码修改";
    self.pwdAlertView.hidden = YES;
    [self.view addSubview:_pwdAlertView];
    
    self.pwdAlertView.pressSureBtn = ^(NSString *oldpwd, NSString *newpwd, NSString *checkpwd){
        
        
        NSString *origPassword = oldpwd;
        NSString *newPassword = newpwd;
        NSString *confirmPassword = checkpwd;

        if (self.indextag == 1) {
            if ([origPassword length] == 0 || [origPassword length] == 0 || [confirmPassword length] == 0) {
                
                return [SVProgressHUD showErrorWithStatus:@"请输入密码"];
            }
            
            if ([[[AppDelegate globalDelegate].cameraModel getViewPasswordOfChannel:0] isEqualToString:origPassword]) {
                
            } else {
                
                return [SVProgressHUD showErrorWithStatus:@"旧密码错误"];
            }
            
            if (![newPassword isEqualToString:confirmPassword]) {
                
                return [SVProgressHUD showErrorWithStatus:@"新旧密码不匹配"];
            }
            if ([origPassword length] <= 8&&[newPassword length] <= 8&&[confirmPassword length] <= 8 &&[origPassword length] >= 4&&[newPassword length] >= 4&&[confirmPassword length] >= 4) {
                
                
            }else{
                
                return[SVProgressHUD showErrorWithStatus:@"请输入四到八位的密码"];
            }

            [SVProgressHUD showWithStatus:@"设置新密码中..."];
            
            SMsgAVIoctrlSetPasswdReq *structSetPassword = malloc(sizeof(SMsgAVIoctrlSetPasswdReq));
            memset(structSetPassword, 0, sizeof(SMsgAVIoctrlSetPasswdReq));
            memcpy(structSetPassword->newpasswd, [newPassword UTF8String], sizeof(structSetPassword->newpasswd));
            memcpy(structSetPassword->oldpasswd, [origPassword UTF8String], sizeof(structSetPassword->oldpasswd));
            
            [[AppDelegate globalDelegate].cameraModel sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SETPASSWORD_REQ Data:(char *)structSetPassword DataSize:sizeof(SMsgAVIoctrlSetPasswdReq)];
            free(structSetPassword);
            
            [AppDelegate globalDelegate].cameraModel.viewPwd = confirmPassword;
            NSLog(@"change security code(%@) in SecurityCodeController", newPassword);
            __weak typeof(self) weakself = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                
                BOOL success = [[AppDelegate globalDelegate].database executeUpdate:@"UPDATE device SET dev_nickname=?, view_pwd=? WHERE dev_uid=?", [AppDelegate globalDelegate].cameraModel.name, newPassword, [AppDelegate globalDelegate].cameraModel.uid];
                
                if (success == YES) {
                    
                    [SVProgressHUD showSuccessWithStatus:@"设置成功!"];
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:@"设置失败"];
                }
                
                
            });
            
            
            [[AppDelegate globalDelegate] loadDeviceFromDatabase];
            
        }else if (self.indextag == 2){
            
            if ([origPassword length] == 0 || [origPassword length] == 0 || [confirmPassword length] == 0) {
                
                return [SVProgressHUD showErrorWithStatus:@"请输入密码"];
            }
            
            if ([self.doorpassword isEqualToString:origPassword]) {
                
            } else {
                
                return [SVProgressHUD showErrorWithStatus:@"旧密码错误"];
            }
            
            if (![newPassword isEqualToString:confirmPassword]) {
                
                return [SVProgressHUD showErrorWithStatus:@"新旧密码不匹配"];
            }
            
            if ([origPassword isMobileNumber]&&[origPassword length] <= 8&&[newPassword isMobileNumber]&&[newPassword length] <= 8&&[confirmPassword isMobileNumber]&&[confirmPassword length] <= 8 &&[origPassword isMobileNumber]&&[origPassword length] >= 4&&[newPassword isMobileNumber]&&[newPassword length] >= 4&&[confirmPassword isMobileNumber]&&[confirmPassword length] >= 4) {
                return[SVProgressHUD showErrorWithStatus:@"请输入四到八位的数字密码"];

                
            }else{
                
            }
            
            SMsgAVIoctrlSetPasswdReq *s = (SMsgAVIoctrlSetPasswdReq *)malloc(sizeof(SMsgAVIoctrlSetPasswdReq));
            memset(s, 0, sizeof(SMsgAVIoctrlSetPasswdReq));
            
            
            memcpy(s->newpasswd, [newPassword UTF8String], sizeof(s->newpasswd));
            memcpy(s->oldpasswd, [origPassword UTF8String], sizeof(s->oldpasswd));
            
            [[AppDelegate globalDelegate].cameraModel sendIOCtrlToChannel:0
                                                                     Type:IOTYPE_USER_IPCAM_SET_DOORPASSWORD_REQ
                                                                     Data:(char *)s
                                                                 DataSize:sizeof(SMsgAVIoctrlSetPasswdReq)];
            
            free(s);
            
            [SVProgressHUD showSuccessWithStatus:@"设置成功"];
            [[AppDelegate globalDelegate] loadDeviceFromDatabase];

        }
        
        weakself.pwdAlertView.hidden = YES;
        
       
    };
    
    self.pwdAlertView.pressCancelBtn = ^(){
        
        weakself.pwdAlertView.hidden = YES;
        
    };

}

#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DSChangePwdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DSChangePwdTableViewCell"];
    
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    switch (indexPath.row) {
        case 0:
        {
            cell.tipLabel.text = @"设备密码";
            cell.contentLabel.text = @"指的是绑定设备的密码";
            cell.changePwdButton.tag = 1;
            [cell.changePwdButton addTarget:self action:@selector(presentAlertViewAction:) forControlEvents:UIControlEventTouchDown];
            
            break;
        }
        case 1:
        {
            cell.tipLabel.text = @"开锁密码";
            cell.contentLabel.text = @"指的是远程开锁的密码";
            cell.changePwdButton.tag = 2;
            [cell.changePwdButton addTarget:self action:@selector(presentAlertViewAction:) forControlEvents:UIControlEventTouchDown];
            break;
        }
        default:
            break;
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}
#pragma mark - --------------------------UITableView delegate--------------------------

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}

#pragma mark - --------------------------touch event--------------------------

- (void)presentAlertViewAction:(UIButton *)sender{

    self.pwdAlertView.oldpwd.text = nil;
    self.pwdAlertView.newpwd.text = nil;
    self.pwdAlertView.checkpwd.text = nil;
    if (sender.tag == 1) {
        
        self.pwdAlertView.title.text = @"设备密码修改";

    }else if (sender.tag == 2){
        
        self.pwdAlertView.title.text = @"开锁密码修改";

    }
    self.indextag = sender.tag;

    
    self.pwdAlertView.hidden = NO;

    
    
  
}

#pragma mark - CameraDelegate Methods

- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    
    if (camera_ == [AppDelegate globalDelegate].cameraModel && type == IOTYPE_USER_IPCAM_GET_DOORPASSWORDMODE_RESP) {
        
        SMsgAVIoctrlGetDoorPasswordModeResp *s = (SMsgAVIoctrlGetDoorPasswordModeResp *)data;
        
     //  s -> state 0 禁用  1启用
        self.doorpassword = [NSString stringWithFormat:@"%s",s->passwd];
        NSLog(@"门锁密码 :%@",self.doorpassword);
        
    }
    
    
}


- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"DSChangePwdTableViewCell" bundle:nil] forCellReuseIdentifier:@"DSChangePwdTableViewCell"];
    }
    
    return _tableView;
    
}


- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"密码设置" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(superView);
        
    }];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
